
goog.provide('esn.model.AnswerModel');

goog.require('esn.model.QuestionModel');
goog.require('goog.array');
goog.require('goog.object');


/**
 * @param {Object|esn.model.QuestionModel} model A model object from the server
 *     or a QuestionModel object.
 * @constructor
 */
esn.model.AnswerModel = function(model) {
  if (model instanceof esn.model.QuestionModel) {
    this.model_ = {
      'section_id': model.getSectionId(),
      'question_id': model.getId()
    };
  } else {
    this.model_ = model;
  }
};

esn.model.AnswerModel.prototype.getId = function() {
  return this.model_['id'];
};

esn.model.AnswerModel.prototype.getSectionId = function() {
  return this.model_['section_id'];
};

esn.model.AnswerModel.prototype.getQuestionId = function() {
  return this.model_['question_id'];
};

esn.model.AnswerModel.prototype.isSet = function() {
  return this.getValues().length > 0;
};

esn.model.AnswerModel.prototype.getValues = function() {
  return this.model_['values'] || [];
};

esn.model.AnswerModel.prototype.setValues = function(values) {
  values.sort();
  this.model_['values'] = values;
};

esn.model.AnswerModel.prototype.toObject = function() {
  return this.model_;
};

esn.model.AnswerModel.prototype.mergeFrom = function(model) {
  // Set any fields present in the new model that are not in the current model.
  // Note: No existing values are overridden.
  goog.object.forEach(model.toObject(), function(value, key) {
    if (!(key in this.model_)) {
      this.model_[key] = value;
    }
  }, this);
};

esn.model.AnswerModel.prototype.valuesEqual = function(values) {
  values.sort();
  if (this.getValues().length != values.length) {
    return false;
  }
  // Since both lists of values are sorted we can compare them in order.
  return goog.array.every(values, function(value, index) {
    return value == this.model_['values'][index];
  }, this);
};

esn.model.AnswerModel.prototype.equals = function(model) {
  return (this.valuesEqual(model.getValues()) &&
          model.getId() == this.getId() &&
          model.getSectionId() == this.getSectionId() &&
          model.getQuestionId() == this.getQuestionId());
};
